package com.megvii.koala.tv.data;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;

import com.megvii.corelib.util.SharedPreferenceTool;
import com.megvii.koala.guard.Box;
import com.megvii.koala.guard.BoxSearcher;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * Created by linyue on 16/1/24.
 */
public class TVBoxManager implements BoxSearcher.BoxSearcherListener
{
    private static String KEY_BOX_INFO = "KEY_BOX_INFO";

    private static int ID_COUNT = 0;

    private Context context;

    private String selectedBoxInfo;

    private BoxSearcher searcher;

    private List<Box> boxes;

    private HashSet<String> tokens;

    private Handler handler;

    private List<TVBoxManagerListener> listeners;

    public static String getAddressByBoxInfo(String boxInfo)
    {
        if (boxInfo != null)
        {
            String[] splitted = boxInfo.split(",");
            String address = splitted[1];
            return address;
        }
        else
        {
            return null;
        }
    }

    public static String getTokenByBoxInfo(String boxInfo)
    {
        if (boxInfo != null)
        {
            String[] splitted = boxInfo.split(",");
            String address = splitted[0];
            return address;
        }
        else
        {
            return null;
        }
    }

    public static String createBoxInfo(String token, String address)
    {
        return token + "," + address;
    }

    public void init(Context context)
    {
        this.context = context;
        selectedBoxInfo = SharedPreferenceTool.getStringValueByKey(context, KEY_BOX_INFO, null);
        searcher = new BoxSearcher();
        searcher.setListener(this);
        searcher.start();
        boxes = new ArrayList<>();
        tokens = new HashSet<>();
        handler = new Handler(Looper.getMainLooper());
        listeners = new ArrayList<>();
    }

    public void release()
    {
        listeners = null;
        if (searcher != null)
        {
            searcher.release();
            searcher = null;
        }
        boxes = null;
        tokens = null;
    }

    public void search()
    {
        synchronized (this)
        {
            boxes.clear();
            tokens.clear();
            searcher.search();
        }
    }

    public List<Box> getBoxes()
    {
        return boxes;
    }

    public Box getBox(int position)
    {
        return boxes.get(position);
    }

    public List<String> getTokens()
    {
        ArrayList<String> result = new ArrayList<>();
        result.addAll(this.tokens);
        return result;
    }

    public List<String> getAddresses()
    {
        ArrayList<String> address = new ArrayList<>();
        for (Box box : boxes)
        {
            address.add(box.address);
        }
        return address;
    }

    public void selectBox(Box box)
    {
        selectedBoxInfo = createBoxInfo(box.token, box.address);
        SharedPreferenceTool.saveStringValue(context, KEY_BOX_INFO, selectedBoxInfo);
        for (TVBoxManagerListener listener : listeners)
        {
            listener.onSelectionChanged(box);
        }
    }

    public void clearSelection()
    {
        selectedBoxInfo = null;
        SharedPreferenceTool.removeStringCollection(context, KEY_BOX_INFO);
        for (TVBoxManagerListener listener : listeners)
        {
            listener.onClearSelection();
        }
    }

    public String getSelectedToken()
    {
        return getTokenByBoxInfo(selectedBoxInfo);
    }

    public String getSelectedAddress()
    {
        return getAddressByBoxInfo(selectedBoxInfo);
    }

    public boolean selected()
    {
        return selectedBoxInfo != null && !selectedBoxInfo.isEmpty();
    }

    @Override
    public void onNewBoxSearched(final String response)
    {
        //TODO
        synchronized (this)
        {
            String address = getAddressByBoxInfo(response);
            String token = getTokenByBoxInfo(response);
            addBox(address, token);
        }
    }

    public boolean addBox(String address, String token)
    {
        synchronized (this)
        {
            if (tokens.contains(token))
            {
                return false;
            }
            else
            {
                final Box box = new Box(ID_COUNT++, address, token, 0, "0");
                box.valid = true;
                boxes.add(box);
                tokens.add(token);
                handler.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        for (TVBoxManagerListener listener : listeners)
                        {
                            listener.onNewBoxSearched(box);
                        }
                    }
                });
                return true;
            }
        }
    }

    public void registerListener(TVBoxManagerListener listener)
    {
        listeners.add(listener);
    }

    public void unregisterListener(TVBoxManagerListener listener)
    {
        listeners.remove(listener);
    }

    public interface TVBoxManagerListener
    {
        public void onNewBoxSearched(Box box);

        public void onSelectionChanged(Box box);

        public void onClearSelection();
    }
}
